package com.hzit.cart.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 类名：
 * 作者：WF
 * 功能：登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

	//1. 本地线程变量，存放的是同一个线程的变量，这里我们存放的是登录的用户名
	public static ThreadLocal<String> local = new ThreadLocal<>();

	// 此方法，返回true，代表放行，返回false，代表阻止
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//1.1 得到session
		HttpSession session = request.getSession();
		//1.2 得到用户名
		Map<String,String> map = (Map<String, String>) session.getAttribute("userInfo");
		if(map == null){    // 证明此时用户没有登录
			String requestURI = request.getRequestURI();
			System.out.println("requestURI = " + requestURI);
			String login_url = "http://thirdparty.hzit.com/user/login?return_url=http://cart.hzit.com" + requestURI;
			response.sendRedirect(login_url);
			return false;
		}
		//1.3 证明用户登录过
		//1.3.1  得到用户名
		String name = map.get("name") + "";
		//1.3.2  将此值放到本地线程变量中
		local.set(name);

		return true;
	}
}
